package com.carey.blog.action.impl;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.carey.blog.framework.latke.Keys;
import com.carey.blog.model.Article;
import com.carey.blog.repository.ArticleRepository;
import com.carey.blog.repository.impl.ArticleGAERepository;

/**
 * Gets some articles randomly and regenerate their random double.
 * 
 */
public final class ArticleRandomDoubleUpdateServlet extends HttpServlet {

	/**
	 * Default serial version uid.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(ArticleRandomDoubleUpdateServlet.class.getName());
	/**
	 * Article repository.
	 */
	private ArticleRepository articleRepository = ArticleGAERepository
			.getInstance();
	/**
	 * Default update count.
	 */
	private static final int DEFAULT_UPDATE_CNT = 10;

	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		int updateCnt = DEFAULT_UPDATE_CNT;
		try {
			updateCnt = Integer.valueOf(request.getParameter("cnt"));
		} catch (final NumberFormatException e) {
			LOGGER.log(Level.WARNING, e.getMessage(), e);
		}

		try {
			final List<JSONObject> randomArticles = articleRepository
					.getRandomly(updateCnt);

			for (final JSONObject article : randomArticles) {
				article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
				articleRepository.updateAsync(
						article.getString(Keys.OBJECT_ID), article);
			}
		} catch (final Exception e) {
			LOGGER.log(Level.WARNING, "Updates article random value failed.");
		}
	}
}
